package cn.ibizlab.util.helper;

import cn.ibizlab.util.domain.DTOBase;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.*;
import cn.ibizlab.util.domain.RequestWrapper;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class RequestWrapperDeserializer<T extends DTOBase> extends JsonDeserializer<RequestWrapper<T>> implements ContextualDeserializer {

    private JavaType type;

    public RequestWrapperDeserializer() {

    }
    public RequestWrapperDeserializer(JavaType type) {
        this.type = type;
    }
    @Override
    public RequestWrapper deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        RequestWrapper<T> wrapper = new RequestWrapper<T>();
        Class<T> cls = (Class<T>) type.getBindings().getBoundType(0).getRawClass();
        if(p.getCurrentToken() == JsonToken.START_ARRAY) {
            // 解析数组格式
            List<T> list = new ArrayList<>();

            // 解析数组每个元素
            while (p.nextToken() != JsonToken.END_ARRAY) {
                T item = ctxt.readValue(p, cls);
                list.add(item);
            }

            wrapper.setList(list);
        } else {
            T object = ctxt.readValue(p, cls);
            wrapper.setDto(object);
        }
        return wrapper;
    }


    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
        JavaType type = ctxt.getContextualType() != null
                ? ctxt.getContextualType()
                : property.getMember().getType();
        return new RequestWrapperDeserializer<>(type);
    }
}